<!-- 案场输入选择框 -->
<template>
  <div class="build-input">
    <Select
      v-model="value"
      filterable
      :loading="loading"
      :remote-method="remoteMethod"
      @on-change="onChange"
    >
      <template v-for="{ housesId, housesName, orgName } in options">
        <Option :value="housesId" :key="housesId">{{ housesName }}({{ orgName }})</Option>
      </template>
    </Select>
  </div>
</template>

<script>
  import buildMgr from '@/biz/building'
  
  export default {
    name: "buildInput",
    props: {
    	buildingName: String,
    },
    data() {
      return {
        value: '',
        options: [],
        loading: false,
      }
    },
    mounted() {
      console.log(this.buildingName)
      if (this.buildingName) {
        this.getBuildings(this.buildingName).then(() => {
          this.value = this.options[0].housesId
          this.$emit('build', this.value, this.options[0])
        })
      }
    },
    methods: {
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true
          setTimeout(() => {
            this.loading = false
            this.getBuildings(query)
          }, 200)
        } else {
          this.options = []
        }
      },
      onChange(item) {
        this.$emit('build', this.value, this.options.find(i => i.housesId === this.value))
      },
      getBuildings(query) {
        return buildMgr.buildsForName(query).then(res => {
          this.options = [...res]
        })
      },
    },
    watch: {
      buildingName(val, oldVal) {
        if (val) {
          this.getBuildings(val).then(() => {
            this.value = this.options[0].housesId
            this.$emit('build', this.value, this.options[0])
          })
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
</style>
